//
//  CycleScrollView.m
//  CustomTabBar
//
//  Created by Maple on 15/8/5.
//  Copyright (c) 2015年 Maple. All rights reserved.
//

#import "KGGamePlaySpecailLoopScrollView.h"
#import "NSTimer+Addition.h"
#import "SDImageCache.h"
#import "UIImageView+WebCache.h"
#define BOTTOM_VIEW_HEIGHT 50.0f
#define LAYER_HEIGHT 26.0f
#define LABEL_HEIGHT 20.0f
#define TIP_IMAGE_SIZE 40.0f


@interface KGGamePlaySpecailLoopScrollView () <UIScrollViewDelegate>{
}

@property (nonatomic , assign) NSInteger currentPageIndex;
@property (nonatomic , assign) NSInteger totalPageCount;
@property (nonatomic , strong) NSMutableArray *contentViews;
@property (nonatomic , strong) UIScrollView *scrollView;
@property (nonatomic , strong) NSTimer *animationTimer;
@property (nonatomic , assign) NSTimeInterval animationDuration;
@property (nonatomic , strong) NSMutableArray *dataSource;
@property (nonatomic , strong) NSMutableArray *galleryViewList;
@end

@implementation KGGamePlaySpecailLoopScrollView{
    UIPageControl* pageCtrl;
}

- (void)setTotalPagesCount:(NSInteger (^)(void))totalPagesCount
{
    _totalPageCount = totalPagesCount();
    if (_totalPageCount > 0) {
        [self configContentViews];
        if (_totalPageCount>1) {
            [self.animationTimer resumeTimerAfterTimeInterval:self.animationDuration];
        }
    }
}

- (id)initWithFrame:(CGRect)frame animationDuration:(NSTimeInterval)animationDuration
{
    self = [self initWithFrame:frame];
    if (animationDuration > 0.0) {
        self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:(self.animationDuration = animationDuration)
                                                               target:self
                                                             selector:@selector(animationTimerDidFired:)
                                                             userInfo:nil
                                                              repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_animationTimer forMode:NSRunLoopCommonModes];
        [self.animationTimer pauseTimer];
        
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.autoresizesSubviews = YES;
        self.scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        self.scrollView.backgroundColor = [UIColor clearColor];
        self.scrollView.autoresizingMask = 0xFF;
        self.scrollView.contentMode = UIViewContentModeCenter;
        self.scrollView.delegate = self;
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.contentOffset = CGPointMake(CGRectGetWidth(self.scrollView.frame), 0);
        self.scrollView.pagingEnabled = YES;
        [self addSubview:self.scrollView];
        
        pageCtrl = [[UIPageControl alloc] initWithFrame:CGRectMake(0,self.scrollView.frame.size.height-40,self.scrollView.frame.size.width, 30)];  //创建UIPageControl，位置在屏幕最下方。
        pageCtrl.currentPage = 0; //当前页
        pageCtrl.currentPageIndicatorTintColor = [UIColor whiteColor];
        pageCtrl.pageIndicatorTintColor = [UIColor lightGrayColor];
        [self addSubview:pageCtrl];
        
        self.currentPageIndex = 0;
        _galleryViewList = [[NSMutableArray alloc] init];
        _dataSource = [[NSMutableArray alloc] init];
        _contentViews = [[NSMutableArray alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(appWillEnterForeground)
                                                     name:UIApplicationWillEnterForegroundNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(appWillEnterBackground)
                                                     name:UIApplicationDidEnterBackgroundNotification
                                                   object:nil];
    }
    return self;
}


- (void)setGalleryDataSource:(NSArray *)dataList{
    pageCtrl.numberOfPages = dataList.count;
    for (UIView *view in self.scrollView.subviews) {
        [view removeFromSuperview];
    }
    [_galleryViewList removeAllObjects];
    [_dataSource removeAllObjects];
    [_contentViews removeAllObjects];
    [_dataSource addObjectsFromArray:dataList];
    
    int viewCount = 3;
    if ([dataList count]>=2) {
        self.scrollView.contentSize = CGSizeMake(3 * CGRectGetWidth(self.scrollView.frame), CGRectGetHeight(self.scrollView.frame));
    }else{
        viewCount = 1;
        self.scrollView.contentSize = CGSizeMake([dataList count] * CGRectGetWidth(self.scrollView.frame), CGRectGetHeight(self.scrollView.frame));
    }
    
    self.currentPageIndex = 0;
    for (NSInteger i = 0; i<viewCount; i++) {
        
        UIView *contentBgView = [[UIView alloc] initWithFrame:CGRectMake(i * _scrollView.frame.size.width, 0, _scrollView.frame.size.width, _scrollView.frame.size.height)];

        [_galleryViewList addObject:contentBgView];
        
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:contentBgView.bounds];
        imageView.backgroundColor = [UIColor clearColor];
        imageView.userInteractionEnabled = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.tag = 1000+i;
        [contentBgView addSubview:imageView];
    
    }
    
    _totalPageCount = [dataList count];
    if (_totalPageCount > 0) {
        [self configContentViews];
        if ([dataList count]>1) {
            [self.animationTimer resumeTimerAfterTimeInterval:self.animationDuration];
        }else{
            [self.animationTimer invalidate];
        }
        
    }
}

#pragma mark -
#pragma mark - 私有函数

- (void)configContentViews
{
    
    [self setScrollViewContentDataSource];
    if ([_galleryViewList count]>=2) {
        [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0)];
    }else{
        [_scrollView setContentOffset:CGPointZero];
    }
    if (self.ChangePageBlock) {
        pageCtrl.currentPage = self.currentPageIndex;
        self.ChangePageBlock(self.currentPageIndex);
    }
}

/**
 *  设置scrollView的content数据源，即contentViews
 */
- (void)setScrollViewContentDataSource
{
    if ([_galleryViewList count]>0) {
        if ([self.contentViews count]==0) {
            for (NSInteger i = 0;i<[_galleryViewList count];i++) {
                UIView *contentBgView = [_galleryViewList objectAtIndex:i];
                UIImageView *imageView = (UIImageView *)[contentBgView viewWithTag:1000+i];
                UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(contentViewTapAction:)];
                [imageView addGestureRecognizer:tapGesture];
                [self.contentViews addObject:contentBgView];
                [self.scrollView addSubview:contentBgView];
            }
        }
        
        if ([_galleryViewList count]<2) {
            NSString *imageUrl = [_dataSource objectAtIndex:0];
            UIView *contentBgView = [_galleryViewList objectAtIndex:0];
            UIImageView *imageView = (UIImageView *)[contentBgView viewWithTag:1000];
            [self setImageView:imageView imageUrl:imageUrl];
            
            UIView *bottomView = (UIImageView *)[contentBgView viewWithTag:2000];
            UIImageView *tipImageView = (UIImageView *)[bottomView viewWithTag:3000];
            UILabel *contentLabel = (UILabel *)[bottomView viewWithTag:4000];

            
        }else{
            NSInteger previousPageIndex;
            NSInteger rearPageIndex;
            
            if ([_galleryViewList count]==2) {
                previousPageIndex = [self getValidateSecondNextPageIndexWithPageIndex:self.currentPageIndex - 1];
                rearPageIndex = [self getValidateSecondNextPageIndexWithPageIndex:self.currentPageIndex + 1];
            }else{
                previousPageIndex = [self getValidNextPageIndexWithPageIndex:self.currentPageIndex - 1];
                rearPageIndex = [self getValidNextPageIndexWithPageIndex:self.currentPageIndex + 1];
            }
            
            NSString *previousImageUrl = [_dataSource objectAtIndex:previousPageIndex];
            UIView *pContentBgView = [_galleryViewList objectAtIndex:0];
            UIImageView *previousImageView = (UIImageView *)[pContentBgView viewWithTag:1000];
            previousImageView.image = [UIImage imageNamed:self.placeHoldImageName];
            [self setImageView:previousImageView imageUrl:previousImageUrl];
            UIView *bottomView = (UIImageView *)[pContentBgView viewWithTag:2000];
            UIImageView *tipImageView = (UIImageView *)[bottomView viewWithTag:3000];
            UILabel *contentLabel = (UILabel *)[bottomView viewWithTag:4000];
            
            
//
            previousImageUrl = [_dataSource objectAtIndex:_currentPageIndex];
            pContentBgView = [_galleryViewList objectAtIndex:1];
            previousImageView = (UIImageView *)[pContentBgView viewWithTag:1001];
            previousImageView.image = [UIImage imageNamed:self.placeHoldImageName];
            [self setImageView:previousImageView imageUrl:previousImageUrl];
            bottomView = (UIImageView *)[pContentBgView viewWithTag:2001];
            tipImageView = (UIImageView *)[bottomView viewWithTag:3001];
            contentLabel = (UILabel *)[bottomView viewWithTag:4001];
            
            
            previousImageUrl = [_dataSource objectAtIndex:rearPageIndex];
            pContentBgView = [_galleryViewList objectAtIndex:2];
            previousImageView = (UIImageView *)[pContentBgView viewWithTag:1002];
            previousImageView.image = [UIImage imageNamed:self.placeHoldImageName];
            [self setImageView:previousImageView imageUrl:previousImageUrl];
            bottomView = (UIImageView *)[pContentBgView viewWithTag:2002];
            tipImageView = (UIImageView *)[bottomView viewWithTag:3002];
            contentLabel = (UILabel *)[bottomView viewWithTag:4002];
            
        }
        
    }else{
        for (UIView *view in self.contentViews) {
            [view removeFromSuperview];
        }
        [self.contentViews removeAllObjects];
    }
    
}


- (void)setImageView:(UIImageView *)imageView imageUrl:(NSString *)imageUrl{
    
    UIImage *fetchImage = nil;
    SDImageCache *imageCache = [SDImageCache sharedImageCache];
    
    if ([imageUrl hasPrefix:@"http"]) {
        
        fetchImage = [imageCache imageFromDiskCacheForKey:imageUrl];
        if(fetchImage){
            [imageView setImage:fetchImage];
            
        }else{
            
            [imageView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:self.placeHoldImageName] completed:^(UIImage *image,NSError *error,SDImageCacheType cacheType){
            }];
            
        }
        
    }
}

- (NSInteger)getValidNextPageIndexWithPageIndex:(NSInteger)currentPageIndex
{
    if(currentPageIndex == -1) {
        return self.totalPageCount - 1;
    } else if (currentPageIndex == self.totalPageCount) {
        return 0;
    } else {
        return currentPageIndex;
    }
}

- (NSInteger)getValidateSecondNextPageIndexWithPageIndex:(NSInteger)currentPageIndex{
    if(currentPageIndex == -1) {
        return 1;
    } else if (currentPageIndex == 2) {
        return 0;
    } else {
        return currentPageIndex;
    }
}

#pragma mark -
#pragma mark - UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.animationTimer pauseTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self.animationTimer resumeTimerAfterTimeInterval:self.animationDuration];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int contentOffsetX = scrollView.contentOffset.x;
    if ([_galleryViewList count]>1) {
        if ([_galleryViewList count]==2) {
            if(contentOffsetX >= (2 * CGRectGetWidth(scrollView.frame))) {
                self.currentPageIndex = [self getValidateSecondNextPageIndexWithPageIndex:self.currentPageIndex + 1];
                [self configContentViews];
            }
            if(contentOffsetX <= 0) {
                self.currentPageIndex = [self getValidateSecondNextPageIndexWithPageIndex:self.currentPageIndex - 1];
                [self configContentViews];
            }
            
        }else{
            if(contentOffsetX >= (2 * CGRectGetWidth(scrollView.frame))) {
                self.currentPageIndex = [self getValidNextPageIndexWithPageIndex:self.currentPageIndex + 1];
                [self configContentViews];
            }
            if(contentOffsetX <= 0) {
                self.currentPageIndex = [self getValidNextPageIndexWithPageIndex:self.currentPageIndex - 1];
                [self configContentViews];
            }
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if ([_galleryViewList count]>1) {
        [scrollView setContentOffset:CGPointMake(CGRectGetWidth(scrollView.frame), 0) animated:YES];
    }
    
}

#pragma mark -
#pragma mark - 响应事件

- (void)animationTimerDidFired:(NSTimer *)timer
{
    if ([_galleryViewList count]==2) {
        _currentPageIndex++;
        if(_currentPageIndex >= [_galleryViewList count]){
            _currentPageIndex = 0;
            if (self.ChangePageBlock) {
                
                self.ChangePageBlock(self.currentPageIndex);
            }
        }
        [self.scrollView setContentOffset:CGPointMake(_currentPageIndex * self.scrollView.frame.size.width, 0) animated:NO];
    }else{
        CGPoint newOffset = CGPointMake(self.scrollView.contentOffset.x + CGRectGetWidth(self.scrollView.frame), self.scrollView.contentOffset.y);
        [self.scrollView setContentOffset:newOffset animated:YES];
    }
}
#pragma mark --page设置当前颜色 
- (void)contentViewTapAction:(UITapGestureRecognizer *)tap
{
    if (self.TapActionBlock) {
        pageCtrl.currentPage = self.currentPageIndex;
        self.TapActionBlock(self.currentPageIndex);
    }
}
- (void)appWillEnterForeground{
    [self.animationTimer resumeTimerAfterTimeInterval:self.animationDuration];
}

- (void)appWillEnterBackground{
    [self.animationTimer pauseTimer];
}

- (void)dealloc{
    if (self.animationTimer) {
        [self.animationTimer invalidate];
        self.animationTimer = nil;
    }
    _placeHoldImageName = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}


@end
